﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYLitedbBase;

namespace DSPara
{
    public class Entity_SDPara : TYLitedbBase.Entity_LiteDB_Base
    {
        public string SectionId { get; set; }
        public List<Entity_SDItem> ListSDItem { get; set; } = new List<Entity_SDItem>();
    }

    public class Entity_SDItem : TYLitedbBase.Entity_LiteDB_Base
    {
        public int AtLevel { get; set; }

        public string SD { get; set; }
    }

    public class SDHelper
    {
        public string SectionId { get; set; }
        public List<Entity_SDItem> ListSSDItem { get; set; }
        private int SSDCount = 0;

        public SDHelper(string section, int sSDCount)
        {
            SectionId = section;
            SSDCount = sSDCount;
            ListSSDItem = new List<Entity_SDItem>();
            for (int i = 0; i < sSDCount; i++)
            {
                ListSSDItem.Add(new Entity_SDItem { AtLevel = i + 1, SD = "" });
            }
        }

        public Entity_SDItem GetSD(int fromSSD)
        {
            var data = ListSSDItem.FirstOrDefault(x => x.AtLevel == fromSSD);
            if (data != null)
                return data;
            return null;
        }

        public void Init(Entity_SDPara listData)
        {
            if (listData == null)
                return;
            for (int i = 0; i < ListSSDItem.Count; i++)
            {
                var data = listData.ListSDItem.FirstOrDefault(x => x.AtLevel == ListSSDItem[i].AtLevel);
                if (data != null)
                {
                    ListSSDItem[i].SD = data.SD;
                }
            }
        }
    }

    public class SDDataCreator
    {
        private readonly string dbName;

        /// <summary>
        /// 这个是配置的数据库
        /// </summary>
        /// <param name="_dbName"></param>
        public SDDataCreator(string _dbName)
        {
            dbName = _dbName;
        }

        public bool Init(SDHelper offsetPara, ref string error)
        {
            var liteDBHelper = new LiteDB_BaseHelper<Entity_SDPara>(dbName);
            if (liteDBHelper.Get(x => x.SectionId == offsetPara.SectionId, out Entity_SDPara listData))
            {
                if (listData == null)
                {
                    error = "无批次分选!!";
                    return false;
                }
                offsetPara.Init(listData);
                return true;
            }
            else
            {
                error = $" 读取批次分选 异常!section:{offsetPara.SectionId}-本地文件为{LiteDBHelper.GetFileFullPath(dbName)} ";
            }
            return false;
        }
    }
}